/*
 * Copyright 2010 Joshua Smith and Nelson Llewellyn
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package norse.server.resources;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.xml.bind.JAXBException;
import norse.msg.MessageIF;
import norse.msg.NoRSeScanRequestResponse;
import norse.server.Postmaster;
import norse.server.model.ScanResults;

import norse.util.MessageMarshaller;
import norse.util.MessageUnmarshaller;

/**
 * Resource for main NoRSe Server interface.
 */
//TODO: JavaDoc
@Path("serverMain")
public class ServerMainResource
{
    /** Creates a new instance of ServerMainResource */
    public ServerMainResource() throws JAXBException
    {
         marshaller = new MessageMarshaller();
         unmarshaller = new MessageUnmarshaller();
    }

    @Context
    private UriInfo context;

    /**
     * Retrieves representation of an instance of norse.server.ServerMainResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("application/xml")
    public String getXml()
    {
        return ScanResults.getScanResults();
    }

//TODO: JavaDoc
    @POST
    @Consumes("application/xml")
    @Produces("application/xml")
    public String postXML(String _content)
    {
        try
        {
            if (_content == null || _content.isEmpty())
            {
                throw new IllegalArgumentException();
            }

            MessageIF msg = unmarshaller.unmarshallMessage(_content);

            Postmaster pm = Postmaster.getInstance();
            pm.deliverMessage(msg);

            NoRSeScanRequestResponse response
                    = new NoRSeScanRequestResponse(true);
            return marshaller.marshallMessage(response);
        }
        catch (Exception error)
        {
            try
            {
                NoRSeScanRequestResponse response
                        = new NoRSeScanRequestResponse(false);
                return marshaller.marshallMessage(response);
            }
            catch (Exception itReallyHitTheFan)
            {
                return "";
            }
        }
    }

    MessageMarshaller marshaller;
    MessageUnmarshaller unmarshaller;
}
